#coding=utf-8
import os
from down.models import Soft
from down.models import Player
from down.models import Wap
from down.models import SoftCate
from down.models import SoftReply
from down.models import GameCate
from down.models import Game
from down.models import GameReply
from down.models import BookCate
from down.models import Book
from down.models import BookReply


from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.http import HttpRequest
from django.http import HttpResponseRedirect

from django.template import loader
from django.shortcuts import render_to_response
from django.db.models import Q


from django.views.generic import list_detail
from django.shortcuts import get_object_or_404
from django.core.mail import send_mail, BadHeaderError


#资源内容页
def down_detail(request,id,model,template):

    object = get_object_or_404(model, pk=id)

    #extra_context,内容页的额外内容
    
    # Show the detail page
    return list_detail.object_detail(
        request,
        queryset = model.objects.all(),
        object_id = object.id,
        template_name = template
    )

#资源列表页
def down_list(request,id,cate,model,template,page='1'):

    cate_object = get_object_or_404(cate, pk=id)
    list_object = model.objects.filter(cate=cate_object)
    #extra_context,列表页的额外内容
    cate_list = cate.objects.all()

    count = model.objects.filter(cate=cate_object).count()
    page_count = 0
    page_int = int(page)
    yushu = count % 10
    if yushu == 0:
      page_count = count / 10
    else:
      page_count = count / 10 + 1
    
    if count == 0:
        page_count = 1
    if page_int*10 <= count:
        list_object = model.objects.filter(cate=cate_object).order_by('-datetime')[(page_int-1)*10:page_int*10]
    else:
        list_object = model.objects.filter(cate=cate_object).order_by('-datetime')[(page_int-1)*10:count]
    
    cur_page = page_int
    has_prev = False
    has_next = False
    prev_page = 0
    next_page = 0
    if cur_page == 1:
       has_prev = False
    else:
       has_prev = True
       prev_page = cur_page-1
    if cur_page == page_count:
       has_next = False
    else:
       has_next = True
       next_page = cur_page+1
    count_list = range(1,page_count+1)
    
    # Show the list page
    return list_detail.object_list(
        request,
	allow_empty = True,
        queryset = list_object,
        template_name = template,
        extra_context = {"cate_object" : cate_object,"cate_list" : cate_list,"count" : count,
	    'page_count':page_count,'cur_page':cur_page,'has_prev':has_prev,'has_next':has_next,
	    'prev_page':prev_page,'next_page':next_page,'count_list':count_list
	
	}
    )

#index页
def index(request):
      
    soft_cate = SoftCate.objects.all()
    game_hot = Game.hots.all()[:10]
    soft_hot = Soft.objects.order_by("-downcount")[:10]
    #soft_hot = soft_hot[:10]
    return render_to_response('down/index.html',{"soft_cate":soft_cate,"game_hot":game_hot,"soft_hot":soft_hot})

#资源index页
def down_index(request,id,model,template):

    cate_object = get_object_or_404(cate, pk=id)

    #extra_context,列表页的额外内容
    
    # Show the list page
    return list_detail.object_list(
        request,
        queryset = model.objects.filter(cate=cate_object),
        template_name = template,
        extra_context = {"cate_object" : cate_object}
    )



#发送Email
def send_email(request):
    subject = request.POST.get('subject', '')
    message = request.POST.get('message', '')
    from_email = request.POST.get('from_email', '')
    to_email = request.POST.get('to_email', '')
    if subject and message and from_email:
        try:
            send_mail(subject, message, from_email, [to_email])
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return HttpResponseRedirect('/contact/thanks/')
    else:
        # In reality we'd use a manipulator
        # to get proper validation errors.
        return HttpResponse('Make sure all fields are entered and valid.')

def show_email_page(request):
    return render_to_response('send_mail.html',{})

def send_email_thanks(request):
    return render_to_response('send_mail_thanks.html',{})

#下载文件，下载次数增1
def down_file_by_id(request,id,model):
    
    object = get_object_or_404(model, pk=id)
    #index = object.downaddr.rfind('.')
    #index1 = object.downaddr.rfind('\\')
    #文件名
    #filename = object.downaddr[index1+1:]
    #扩展名
    #ext = object.downaddr[index+1:]
    #mimetype_str = 'application/'+ext
    
    #response = HttpResponse(mimetype=mimetype_str)
    #cond = 'attachment; filename='+filename
    #response['Content-Disposition'] = cond
    #写文件内容
    

    #下载次数增1
    object.downcount = str(int(object.downcount) + 1)
    object.save()
    addr = object.downaddr.replace('\\','/')
    url = '/site_media/' + addr
    return HttpResponseRedirect(url)
    

#显示TOP.html
def show_top(request,cate):
    
    cate_list = cate.objects.all()

    return render_to_response('down/top.html',{'cate_list' : cate_list})

#搜索
def search(request):

    q_mobileType = request.GET.get('mobileType', '')
    print q_mobileType
    q_type = request.GET.get('type', '')
    print q_type
    q_key = request.GET.get('key', '')
    if q_key == '关键字' or q_key == '':
        if q_type == '0':
	    qset = (
               #Q(name__icontains=q_key) |
	       #Q(cate=q_type) &
               Q(os__icontains=q_mobileType)
            )
	else:
	    qset = (
               #Q(name__icontains=q_key) |
	       Q(cate=q_type) &
               Q(os__icontains=q_mobileType)
            )
    else :
        if q_type == '0':
	    qset = (
               Q(name__icontains=q_key) &
	       #Q(cate=q_type) &
               Q(os__icontains=q_mobileType)
            )
	else:
	    qset = (
               Q(name__icontains=q_key) &
	       Q(cate=q_type) &
               Q(os__icontains=q_mobileType)
            )
    

    object_list = Soft.objects.filter(qset).distinct()
    
    return render_to_response("down/search.html", {
        "object_list": object_list})

    



#显示WAP,成功
def show_wap_index(request):
    return HttpResponse(loader.render_to_string('wap/index.wml',{}),"text/vnd.wap.wml")
    #return render_to_response('wap/index.wml',{})

def show_wap_bookmark(request):
    
    return render_to_response('wap/bookmark.wmlc',{})